<template>
  <div class="chat-window">
    <div class="top">
      <div class="head-pic">
        <HeadPortrait :imgUrl="frinedInfo.headImg"></HeadPortrait>
      </div>
      <div class="info-detail">
        <div class="name">{{ frinedInfo.name }}</div>
        <div class="detail">{{ frinedInfo.detail }}</div>
      </div>
      <div class="other-fun">
        <span class="iconfont icon-shipin" @click="video"> </span>
        <span class="iconfont icon-gf-telephone" @click="telephone"></span>
        <label for="docFile">
          <span class="iconfont icon-wenjian"></span>
        </label>
        <label for="imgFile">
          <span class="iconfont icon-tupian"></span>
        </label>
        <input type="file" name="" id="imgFile" @change="sendImg" accept="image/*"/>
        <input type="file" name="" id="docFile" @change="sendFile" accept="application/*,text/*"/>
      </div>
    </div>
    <div class="botoom">
      <div class="chat-content" ref="chatContent">
        <div class="chat-wrapper" v-for="(item, index) in chatList" :key="item.id">
          <div class="chat-friend" v-if="item.uid !== '1001'">
            <div class="info-time">
              <img :src="item.headImg" alt=""/>
              <span>{{ item.name }}</span>
              <span>{{ item.time }}</span>
            </div>
            <div class="chat-text" v-if="item.chatType == 0">
              <template v-if="isSend && index == chatList.length - 1">
                <span class="flash_cursor"></span>
              </template>
              <el-collapse v-if="item.reasoningContent" v-model="activeCollapse" style="margin-bottom: 10px;">
                <el-collapse-item name="1">
                  <template #title>
                    <span v-if="activeCollapse.includes('1')">Thinking</span>
                    <span v-else>click to expand</span>
                  </template>
                  <pre>{{ item.reasoningContent }}</pre>
                </el-collapse-item>
              </el-collapse>
              <template v-if="item.msg">
                <pre>{{ item.msg }}</pre>
              </template>
            </div>
            <div class="related-docs" v-if="item.relatedDocs">
              <div v-for="(doc, docIndex) in item.relatedDocs" :key="docIndex" @click="showContent(doc.content)"
                   class="related-doc-item">
                {{ doc.fileId }}
              </div>
            </div>
          </div>
          <div class="chat-me" v-else>
            <div class="info-time">
              <span>{{ item.name }}</span>
              <span>{{ item.time }}</span>
              <img :src="item.headImg" alt=""/>
            </div>
            <div class="chat-text" v-if="item.chatType == 0">
              {{ item.msg }}
            </div>
          </div>
        </div>
      </div>
      <div class="chatInputs">
        <input class="inputs" placeholder="Content generated by AI, not guaranteed to be accurate, for reference only." v-model="inputMsg"
               @keyup.enter="sendText"/>
        <el-button class="send boxinput" :disabled="isSend" @click="sendText">
          <i class="el-icon-back arrow-icon"></i>
        </el-button>
      </div>
    </div>
    <!-- 模态框 -->
    <el-dialog :visible.sync="dialogVisible" title="文档内容" width="80%" append-to-body>
      <div style="color: white">{{ selectedContent }}</div>
    </el-dialog>
  </div>
</template>

<script>
import {animation} from "@/util/util";
import {getChatMsg, chatgpt} from "@/api/getData";

import HeadPortrait from "@/components/HeadPortrait";
import Emoji from "@/components/Emoji";
import FileCard from "@/components/FileCard.vue";

export default {
  components: {
    HeadPortrait,
    Emoji,
    FileCard,
  },
  props: {
    frinedInfo: Object,
    default() {
      return {};
    },
  },
  watch: {
    frinedInfo() {
      this.getFriendChatMsg();
    },
  },
  data() {
    return {
      chatList: [],
      inputMsg: "",
      showEmoji: false,
      friendInfo: {},
      srcImgList: [],
      isSend: false,
      dialogVisible: false,
      selectedContent: '',
      activeCollapse: ['1'],
    };
  },
  mounted() {
    this.getFriendChatMsg();
  },
  methods: {
    async getRelatedDoc(data) {
      return fetch('http://localhost:8888/api/ollama/chat/deepseek/getRelatedDoc', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      }).then(response => response.json());
    },
    showContent(content) {
      this.selectedContent = content;
      this.dialogVisible = true;
    },
    //获取聊天记录
    getFriendChatMsg() {
      let params = {
        frinedId: this.frinedInfo.id,
      };
      getChatMsg(params).then((res) => {
        this.chatList = res;
        this.chatList.forEach((item) => {
          if (item.chatType == 2 && item.extend.imgType == 2) {
            this.srcImgList.push(item.msg);
          }
        });
        this.chatList[0].time = new Date().toLocaleTimeString();
        this.scrollBottom();
      });
    },
    //发送信息
    sendMsg(msgList) {
      this.chatList.push(msgList);
      this.scrollBottom();
    },
    //获取窗口高度并滚动至最底层
    scrollBottom() {
      this.$nextTick(() => {
        const scrollDom = this.$refs.chatContent;
        animation(scrollDom, scrollDom.scrollHeight - scrollDom.offsetHeight);
      });
    },
    async sendText() {
      if (this.inputMsg) {
        let chatMsg = {
          headImg: require("@/assets/img/head_portrait.jpg"),
          name: "Planker",
          time: new Date().toLocaleTimeString(),
          msg: this.inputMsg,
          chatType: 0, // 信息类型，0文字，1图片
          uid: "1001", // uid
        };
        this.sendMsg(chatMsg);
        this.$emit('personCardSort', this.frinedInfo.id);
        this.inputMsg = "";

        // 构造消息对象
        let messages = this.chatList.map(item => ({
          role: item.uid === "1001" ? "user" : "assistant",
          content: item.msg,
        }));

        let data = {
          messages: messages.slice(1),
        };
        this.isSend = true;


        let chatGPT = {
          headImg: require("@/assets/img/head_portrait1.jpg"),
          name: "Bytesforce AI",
          time: new Date().toLocaleTimeString(),
          msg: "",
          chatType: 0, // 信息类型，0文字，1图片
          uid: "1002", // uid
          reasoningContent: "",
          relatedDocs: [],
        };
        this.sendMsg(chatGPT);
        this.chatList[this.chatList.length - 1].relatedDocs = await this.getRelatedDoc(
            data
        )
        console.log(this.chatList[this.chatList.length - 1].relatedDocs)
        try {
          const resp = await fetch('http://localhost:8888/api/ollama/chat/localKnowledge', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
          });
          const reader = resp.body.getReader();
          let buffer = ''; // Initialize buffer to accumulate chunks of data
          let firstBuffer = true
          while (true) {
            const {done, value} = await reader.read();
            this.isSend = false;
            if (done) {
              console.log("done");
              console.log(this.chatList[this.chatList.length - 1].msg)
              this.$message.success("回答完毕");
              break;
            }
            const decodedValue = new TextDecoder().decode(value);
            buffer += decodedValue; // Accumulate the data
            if (firstBuffer) {
              buffer = this.extractSecondJson(buffer)
              firstBuffer = false
            }
            if (!buffer) {
              continue
            }

            // Look for a complete JSON object in the buffer
            let jsonStartIndex = buffer.indexOf('{');
            let jsonEndIndex = buffer.lastIndexOf('}');

            if (jsonStartIndex !== -1 && jsonEndIndex !== -1 && jsonEndIndex > jsonStartIndex) {
              // Extract the potential JSON string
              let jsonString = buffer.substring(jsonStartIndex, jsonEndIndex + 1);
              try {
                const jsonData = JSON.parse(jsonString); // Parse the JSON
                // Extract the content from the response
                const content = jsonData.choices[0].delta.content || '';
                const reasoningContent = jsonData.choices[0].delta.reasoning_content || '';

                if (content) {
                  // Update the last message in the chat list
                  this.chatList[this.chatList.length - 1].msg += content;
                }

                if (reasoningContent) {
                  // Update the last message in the chat list with reasoning content
                  this.chatList[this.chatList.length - 1].reasoningContent += reasoningContent;
                }

                // 强制更新最后一条消息
                this.$set(this.chatList, this.chatList.length - 1, {
                  ...this.chatList[this.chatList.length - 1],
                  msg: this.chatList[this.chatList.length - 1].msg,
                  reasoningContent: this.chatList[this.chatList.length - 1].reasoningContent,
                });
                this.scrollBottom();
                buffer = buffer.substring(jsonEndIndex + 1); // Reset buffer after successful processing
              } catch (parseError) {
                console.error("JSON parsing error:", parseError);
                // If parsing fails, just keep accumulating data and wait for a complete message
                buffer = buffer.substring(jsonEndIndex + 1);
              }
            }
          }
        } catch (error) {
          console.error("Error during API request:", error);
          this.isSend = false;
          this.$message({
            message: "发送消息时出错，请稍后再试。",
            type: "error",
          });
        }
      } else {
        this.$message({
          message: "消息不能为空哦~",
          type: "warning",
        });
      }
    },
    extractSecondJson(str) {
      let firstEndIndex = -1;
      let count = 0;
      let inString = false;
      let escape = false;

      // 查找第一个JSON的结束位置
      for (let i = 0; i < str.length; i++) {
        const char = str[i];
        if (escape) {
          escape = false;
          continue;
        }
        if (char === '\\') {
          escape = true;
        } else if (char === '"') {
          inString = !inString;
        } else if (!inString) {
          if (char === '{') count++;
          else if (char === '}') count--;
        }
        if (count === 0 && firstEndIndex === -1) {
          firstEndIndex = i;
          break;
        }
      }

      if (firstEndIndex === -1) console.log("第一个JSON不完整")

      // 查找第二个JSON的起始位置
      let startIndex = firstEndIndex + 1;
      while (startIndex < str.length && str[startIndex].trim() === '') startIndex++;

      if (startIndex >= str.length || str[startIndex] !== '{') {
        console.log("第二个JSON不存在")
      }

      // 查找第二个JSON的结束位置
      let secondEndIndex = -1;
      count = 1;
      inString = false;
      escape = false;

      for (let i = startIndex + 1; i < str.length; i++) {
        const char = str[i];
        if (escape) {
          escape = false;
          continue;
        }
        if (char === '\\') {
          escape = true;
        } else if (char === '"') {
          inString = !inString;
        } else if (!inString) {
          if (char === '{') count++;
          else if (char === '}') count--;
        }
        if (count === 0) {
          secondEndIndex = i;
          break;
        }
      }

      if (secondEndIndex === -1) console.log("第二个JSON不完整")

      const secondJSON = str.slice(startIndex, secondEndIndex + 1);

      // 验证JSON有效性
      try {
        JSON.parse(secondJSON);
        return secondJSON;
      } catch (e) {
        console.log("第二个JSON不完整")
      }
    },
    //发送表情
    sendEmoji(msg) {
      let chatMsg = {
        headImg: require("@/assets/img/head_portrait.jpg"),
        name: "大毛是小白",
        time: "09：12 AM",
        msg: msg,
        chatType: 1, //信息类型，0文字，1图片
        extend: {
          imgType: 1, //(1表情，2本地图片)
        },
        uid: "1001",
      };
      this.sendMsg(chatMsg);
      this.clickEmoji();
    },
    //发送本地图片
    sendImg(e) {
      let _this = this;
      console.log(e.target.files);
      let chatMsg = {
        headImg: require("@/assets/img/head_portrait.jpg"),
        name: "大毛是小白",
        time: "09：12 AM",
        msg: "",
        chatType: 1, //信息类型，0文字，1图片, 2文件
        extend: {
          imgType: 2, //(1表情，2本地图片)
        },
        uid: "1001",
      };
      let files = e.target.files[0]; //图片文件名
      if (!e || !window.FileReader) return; // 看是否支持FileReader
      let reader = new FileReader();
      reader.readAsDataURL(files); // 关键一步，在这里转换的
      reader.onloadend = function () {
        chatMsg.msg = this.result; //赋值
        _this.srcImgList.push(chatMsg.msg);
      };
      this.sendMsg(chatMsg);
      e.target.files = null;
    },
    //发送文件
    sendFile(e) {
      let chatMsg = {
        headImg: require("@/assets/img/head_portrait.jpg"),
        name: "大毛是小白",
        time: "09：12 AM",
        msg: "",
        chatType: 2, //信息类型，0文字，1图片, 2文件
        extend: {
          fileType: "", //(1word，2excel，3ppt，4pdf，5zpi, 6txt)
        },
        uid: "1001",
      };
      let files = e.target.files[0]; //图片文件名
      chatMsg.msg = files;
      console.log(files);
      if (files) {
        switch (files.type) {
          case "application/msword":
          case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
            chatMsg.extend.fileType = 1;
            break;
          case "application/vnd.ms-excel":
          case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
            chatMsg.extend.fileType = 2;
            break;
          case "application/vnd.ms-powerpoint":
          case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
            chatMsg.extend.fileType = 3;
            break;
          case "application/pdf":
            chatMsg.extend.fileType = 4;
            break;
          case "application/zip":
          case "application/x-zip-compressed":
            chatMsg.extend.fileType = 5;
            break;
          case "text/plain":
            chatMsg.extend.fileType = 6;
            break;
          default:
            chatMsg.extend.fileType = 0;
        }
        this.sendMsg(chatMsg);
        e.target.files = null;
      }
    },
    // 发送语音
    telephone() {
      this.$message("该功能还没有开发哦，敬请期待一下吧~🥳");
    },
    //发送视频
    video() {
      this.$message("该功能还没有开发哦，敬请期待一下吧~🥳");
    },
  },
};
</script>

<style lang="scss" scoped>
.flash_cursor {
  width: 20px;
  height: 30px;
  display: inline-block;
  background: #d6e3f5;
  opacity: 1;
  animation: glow 800ms ease-out infinite alternate;
}

@keyframes glow {
  0% {
    opacity: 1;
  }

  25% {
    opacity: .5;
  }

  50% {
    opacity: 0;
  }

  75% {
    opacity: .5;
  }

  100% {
    opacity: 1;
  }
}

.chat-window {
  width: 100%;
  height: 100%;
  margin-left: 20px;
  position: relative;

  .top {
    margin-bottom: 50px;

    &::after {
      content: "";
      display: block;
      clear: both;
    }

    .head-pic {
      float: left;
    }

    .info-detail {
      float: left;
      margin: 5px 20px 0;

      .name {
        font-size: 20px;
        font-weight: 600;
        color: #fff;
      }

      .detail {
        color: #9e9e9e;
        font-size: 12px;
        margin-top: 2px;
      }
    }

    .other-fun {
      float: right;
      margin-top: 20px;

      span {
        margin-left: 30px;
        cursor: pointer;
      }

      // .icon-tupian {

      // }
      input {
        display: none;
      }
    }
  }

  .botoom {
    width: 100%;
    height: 70vh;
    background-color: rgb(50, 54, 68);
    border-radius: 20px;
    padding: 20px;
    box-sizing: border-box;
    position: relative;

    .chat-content {
      width: 100%;
      height: 85%;
      overflow-y: scroll;
      padding: 20px;
      box-sizing: border-box;

      &::-webkit-scrollbar {
        width: 0;
        /* Safari,Chrome 隐藏滚动条 */
        height: 0;
        /* Safari,Chrome 隐藏滚动条 */
        display: none;
        /* 移动端、pad 上Safari，Chrome，隐藏滚动条 */
      }

      .chat-wrapper {
        position: relative;
        word-break: break-all;

        .chat-friend {
          width: 100%;
          float: left;
          margin-bottom: 20px;
          display: flex;
          flex-direction: column;
          justify-content: flex-start;
          align-items: flex-start;

          .chat-text {
            max-width: 90%;
            padding: 20px;
            border-radius: 20px 20px 20px 5px;
            background-color: rgb(56, 60, 75);
            color: #fff;

            &:hover {
              background-color: rgb(39, 42, 55);
            }

            pre {
              white-space: break-spaces;
            }
          }

          .chat-img {
            img {
              width: 100px;
              height: 100px;
            }
          }

          .info-time {
            margin: 10px 0;
            color: #fff;
            font-size: 14px;

            img {
              width: 30px;
              height: 30px;
              border-radius: 50%;
              vertical-align: middle;
              margin-right: 10px;
            }

            span:last-child {
              color: rgb(101, 104, 115);
              margin-left: 10px;
              vertical-align: middle;
            }
          }
        }

        .chat-me {
          width: 100%;
          float: right;
          margin-bottom: 20px;
          position: relative;
          display: flex;
          flex-direction: column;
          justify-content: flex-end;
          align-items: flex-end;

          .chat-text {
            float: right;
            max-width: 90%;
            padding: 20px;
            border-radius: 20px 20px 5px 20px;
            background-color: rgb(29, 144, 245);
            color: #fff;

            &:hover {
              background-color: rgb(26, 129, 219);
            }
          }

          .chat-img {
            img {
              max-width: 300px;
              max-height: 200px;
              border-radius: 10px;
            }
          }

          .info-time {
            margin: 10px 0;
            color: #fff;
            font-size: 14px;
            display: flex;
            justify-content: flex-end;

            img {
              width: 30px;
              height: 30px;
              border-radius: 50%;
              vertical-align: middle;
              margin-left: 10px;
            }

            span {
              line-height: 30px;
            }

            span:first-child {
              color: rgb(101, 104, 115);
              margin-right: 10px;
              vertical-align: middle;
            }
          }
        }
      }
    }

    .chatInputs {
      width: 90%;
      position: absolute;
      bottom: 0;
      margin: 3%;
      display: flex;

      .boxinput {
        width: 50px;
        height: 50px;
        background-color: rgb(66, 70, 86);
        border-radius: 15px;
        border: 1px solid rgb(80, 85, 103);
        position: relative;
        cursor: pointer;

        img {
          width: 30px;
          height: 30px;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
        }
      }

      .emoji {
        transition: 0.3s;

        &:hover {
          background-color: rgb(46, 49, 61);
          border: 1px solid rgb(71, 73, 82);
        }
      }

      .inputs {
        width: 90%;
        height: 50px;
        background-color: rgb(66, 70, 86);
        border-radius: 15px;
        border: 2px solid rgb(34, 135, 225);
        padding: 10px;
        box-sizing: border-box;
        transition: 0.2s;
        font-size: 20px;
        color: #fff;
        font-weight: 100;
        margin: 0 20px;

        &:focus {
          outline: none;
        }
      }

      .send {
        background-color: rgb(29, 144, 245);
        border: 0;
        transition: 0.3s;
        box-shadow: 0px 0px 5px 0px rgba(0, 136, 255);
        display: flex;
        justify-content: center;
        align-items: center;

        &:hover {
          box-shadow: 0px 0px 10px 0px rgba(0, 136, 255);
        }
      }
    }
  }

  .arrow-icon {
    font-size: 24px; /* 设置图标大小 */
    color: white; /* 设置图标颜色为白色 */
  }
}

.reasoning-content {
  max-width: 90%;
  padding: 10px;
  border-radius: 20px 20px 5px 20px;
  background-color: rgb(40, 44, 59);
  color: #fff;
  margin-top: 10px;

  &:hover {
    background-color: rgb(35, 39, 53);
  }

  pre {
    white-space: break-spaces;
  }
}
</style>

<style scoped>
.related-docs {
  background-color: rgb(39, 42, 55);
  border-radius: 8px;
  color: white;
  padding: 10px;
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  width: auto;
}

.related-doc-item {
  cursor: pointer;
  padding: 5px 10px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  flex: 0 0 calc(33.333% - 10px); /* 每行最多三个，每项占三分之一减去间距 */
  box-sizing: border-box;
  white-space: nowrap;
  color: #a6a4a4;
  font-size: 12px;
}

.related-doc-item:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

/* 折叠组件样式 */
.el-collapse >>> .el-collapse-item__header {
  background-color: #323644; /* 使用主题色 */
  color: white;
  border-bottom: none;
  padding: 10px;
  border-radius: 8px 8px 0 0;
  transition: background-color 0.3s;
}

.el-collapse >>> .el-collapse-item__header.is-active {
  background-color: #323644; /* 使用主题色 */
  border-radius: 8px;
}

.el-collapse >>> .el-collapse-item__wrap {
  background-color: #323644; /* 使用主题色 */
  border-radius: 0 0 8px 8px;
}

.el-collapse >>> .el-collapse-item__content {
  padding: 10px;
  color: white;
}

.el-collapse >>> .el-collapse-item__header.focusing:not(.is-disabled):not(.is-active) {
  color: white;
}

.el-collapse >>> .el-collapse-item__header.is-active {
  color: white;
}

.el-collapse >>> .el-collapse-item__header:hover {
  background-color: #444a59; /* 悬停时的颜色 */
}
</style>

<style>
/* 模态框样式 */
.el-dialog {
  background-color: rgba(39, 42, 55, 0.9); /* 使用主题色并添加透明度以实现毛玻璃效果 */
  border-radius: 16px; /* 圆角 */
  backdrop-filter: blur(10px); /* 毛玻璃效果 */
  color: white; /* 白色文字 */
}

.el-dialog__title {
  color: white; /* 标题文字颜色 */
}

.el-dialog__header {
  background-color: rgba(39, 42, 55, 0.9); /* 标题背景颜色 */
  border-radius: 16px 16px 0 0; /* 圆角 */
}

.el-dialog__body {
  padding: 20px; /* 调整内边距 */
}

.dialog-content {
  white-space: pre-wrap; /* 确保内容换行 */
  word-wrap: break-word; /* 确保长单词换行 */
  color: white; /* 白色文字 */
}

.ai-disclaimer {
  font-size: 0.9em;
  color: #999;
  margin-top: 5px;
}


input::-webkit-input-placeholder {
  /* placeholder字体大小 */
  font-size: 16px;
}
</style>